/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com, guwei8576431@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 *
 * Created on 2009-10-18
 *******************************************************************************/

package org.cgtw.scriptprofile.server.manager;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;

import javax.swing.SwingUtilities;

import org.cgtw.scriptprofile.server.ScriptProfileServer;
import org.cgtw.scriptprofile.server.listener.IProfileLifeCycleListener;
import org.cgtw.scriptprofile.server.model.ProfileSourceInfo;

/**
 * manager the profile server
 */
public class ScriptProfileServerManager {
	private static ScriptProfileServerManager instance = null;

	private ScriptProfileServer server;

	private List<IProfileLifeCycleListener> listeners = new ArrayList<IProfileLifeCycleListener>();

	private ScriptProfileServerManager(){}

	public static ScriptProfileServerManager getInstance(){
		if(instance == null){
			instance = new ScriptProfileServerManager();
		}
		return instance;
	}

	public void startProfile(final ProfileSourceInfo info){
		ServerSocket socketServer = null;
		try {
			socketServer = new ServerSocket(info.getPort());
		} catch (IOException e) {

		}
		if (socketServer == null) {
			return;
		}

		server = new ScriptProfileServer(info, socketServer);
		server.start();

		//open the browser and redirect to the local url
		final String startUrl = server.getLocalBaseUrl()
				+ server.getRemoteBaseUrl().getPath().replace(" ", "+"); //$NON-NLS-1$ //$NON-NLS-2$
		SwingUtilities.invokeLater(new Runnable() {

			public void run() {
				try {
					Runtime.getRuntime().exec(new String[]{
							info.getBrowser() , startUrl}); //$NON-NLS-1$
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		});


		//fire the event at the end
		for(IProfileLifeCycleListener listener : listeners){
			listener.startProfile();
		}
	}

	public void stopProfile(){
		if(server != null){
			server.stop();
			//fire the event at the end
			for(IProfileLifeCycleListener listener : listeners){
				listener.stopProfile();
			}
		}
	}

	public void addListener(IProfileLifeCycleListener listener){
		listeners.add(listener);
	}

	public void removeListener(IProfileLifeCycleListener listener){
		listeners.remove(listener);
	}

	/**
	 * @return Returns the server.
	 */
	public ScriptProfileServer getServer() {
		return server;
	}

}
